package com.zyf.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author zhaoYuFei
 */
@Configuration
public class TotalFiler {
    @Bean
    public GlobalFilter timeFilter(){
        return new TimeFilter();
    }


//    @Bean
//    public GlobalFilter myAuthFilter()
//    {
//        return new MyAuthFilter();
//    }

    @Slf4j
    static class TimeFilter implements GlobalFilter, Ordered {
        private static final String  COMING_TIME = "comingTime";
        @Override
        public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
            exchange.getAttributes().put(COMING_TIME,System.currentTimeMillis());
            return chain.filter(exchange).then(Mono.fromRunnable(()->{
                Long OUT_TIME=exchange.getAttribute(COMING_TIME);
                if (OUT_TIME !=null){
                    log.info("访问接口主机IP:"+exchange.getRequest().getURI().getHost());
                    log.info("访问接口主机端口:"+exchange.getRequest().getURI().getPort());
                    log.info("访问接口主机URL:"+exchange.getRequest().getURI().getPath());
                    log.info("访问接口主机URL后的参数:"+exchange.getRequest().getURI().getRawQuery());
                    log.info("访问接口主机的时长:"+(System.currentTimeMillis()-OUT_TIME)+" 毫秒");
                    log.info("===================================================================");
                }
            }));
        }

        /**
         *
         * @return 优先级为0最大
         */
        @Override
        public int getOrder() {
            return 0;
        }
    }

//
//    @Slf4j
//    static class MyAuthFilter implements GlobalFilter, Ordered {
//
//        @Override
//        public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//            log.info("MyAuthFilter权限过滤器");
//            String token = exchange.getRequest().getHeaders().getFirst("token");
//            if (StringUtils.isBlank(token)) {
//                exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
//                return exchange.getResponse().setComplete();
//            }
//
//            return chain.filter(exchange);
//        }
//
//        @Override
//        public int getOrder() {
//            return HIGHEST_PRECEDENCE + 400;
//        }
//    }

}
